package com.project.controller;

import com.alibaba.fastjson.JSONObject;
import com.project.bean.OrderBean;
import com.project.bean.UserBean;
import com.project.config.properties.WeixinPayProperties;
import com.project.pay.QrCodeRequest;
import com.project.pay.ReportReqData;
import com.project.service.IOrderService;
import com.project.util.codingUtils.RandomStringGenerator;
import com.project.vo.R;
import io.swagger.annotations.Api;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.util.Map;

@RestController
@Log4j2
@Api(tags = "微信支付测试接口")
public class ApiPayController extends ApiBaseController {

    @Autowired
    private WeixinPayProperties weixinProperties;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private QrCodeRequest qrCodeRequest;

    /**
     * 元转换成分
     *
     * @param amount
     * @return
     */
    public static String getMoney(String amount) {
        if (amount == null) {
            return "";
        }
        // 金额转化为分为单位
        // 处理包含, ￥ 或者$的金额
        String currency = amount.replaceAll("\\$|\\￥|\\,", "");
        int index = currency.indexOf(".");
        int length = currency.length();
        Long amLong = 0L;
        if (index == -1) {
            amLong = Long.valueOf(currency + "00");
        } else if (length - index >= 3) {
            amLong = Long.valueOf((currency.substring(0, index + 3)).replace(".", ""));
        } else if (length - index == 2) {
            amLong = Long.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
        } else {
            amLong = Long.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
        }
        return amLong.toString();
    }

    /**
     * 微信小程序支付的接口
     *
     * @param request
     * @param orderCode 订单编号
     * @return
     */
    @GetMapping("/pay")
    public R payVip(HttpServletRequest request, String orderCode) {
        //获得ip地址
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (Exception e) {
                }
                ipAddress = inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        //开始支付,创建数据体
        JSONObject json = new JSONObject();
        // 支付业务
        //1：根据订单编号查询对应订单信息
        OrderBean orderBean = orderService.findByOrderCode(orderCode);
        if (orderBean == null ||orderBean.getStatus()==4) return R.error().code(601).message("订单没找到或者已过期！");
        // 2：获取微信小程序的openid
        UserBean userBean = (UserBean) request.getSession().getAttribute("loginUser");
        //UserBean userBean= JwtUtil.verifierJwt(openid);
        String openid = userBean.getOpenid();
        if (StringUtils.isEmpty(openid)) return R.error().code(601).message("openid没找到!");
        //3：分账接收方用户Id session或者redis
        String userCode = userBean.getUserCode();
        // 组装微信支付数据
        ReportReqData data = new ReportReqData();
        // openid
        data.setOpenid(openid);
        // 签约的类型JSAPI
        data.setTrade_type(weixinProperties.getType());
        // 微信小程序的appid
        data.setAppid(weixinProperties.getAppid());
        // 商户id
        data.setMch_id(weixinProperties.getMchid());
        // 回调地址 需要配置
        data.setNotify_url(weixinProperties.getNotifyPath());
        // 业务数据
        data.setBody("外卖商铺编号：" + orderBean.getShopCode());//套餐名称
        data.setOut_trade_no(orderCode);//订单号
        //data.setProduct_id(productId+"");//商品ID
        data.setSpbill_create_ip(ipAddress);//ip地址
        data.setTotal_fee(getMoney(orderBean.getOrderMoney()));// 金额
        data.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
        json.put("userCode", userCode);
        json.put("type", "orderPay");
        json.put("ip", ipAddress);
        //创建订单
        String params = json.toString().replace("\"", "'");
        log.info("执行支付传递的参数: {}", params);
        data.setAttach(params);
        log.info("操作完毕,开始发起支付");
        //微信支付返回的结果
        Map<String, String> weixinMap = qrCodeRequest.submitWeixinMessage(data);
        return R.ok().data("weixinMap", weixinMap);
    }
}
